﻿using System;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.Exceptions;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using YArchitech.Controls;

namespace HYView
{
	[Regeneration(RegenerationOption.Manual)]
	[Transaction(TransactionMode.Manual)]
	public class CmdFamily3DView : IExternalCommand
	{
		public Result Execute(ExternalCommandData cmdData, ref string messages, ElementSet elements)
		{
			UIApplication application = cmdData.Application;
			Document document = cmdData.Application.ActiveUIDocument.Document;
			Selection selection = cmdData.Application.ActiveUIDocument.Selection;
			RevitVersionFuncs.ClearSelection(selection);
			FormFamily3DView formFamily3DView = new FormFamily3DView();
			formFamily3DView.DialogResult = DialogResult.Abort;
            Autodesk.Revit.DB.View activeView = document.ActiveView;
			for (;;)
			{
				try
				{
					if (formFamily3DView.DialogResult == DialogResult.Abort)
					{
						Reference reference = selection.PickObject(Autodesk.Revit.UI.Selection.ObjectType.Element, "请在当前视图中选择一个族实例");
						FamilyInstance familyInstance = document.GetElement(reference) as FamilyInstance;
						if (familyInstance == null)
						{
							YJKMessageBox.Show("没有得到族实例");
						}
						else
						{
							FamilySymbol symbol = familyInstance.Symbol;
							if (symbol != null)
							{
								formFamily3DView.UpdateElementHost(document, symbol);
							}
							RevitVersionFuncs.ClearSelection(selection);
							formFamily3DView.ShowDialog();
						}
						continue;
					}
				}
				catch (Autodesk.Revit.Exceptions.OperationCanceledException)
				{
				}
				catch (Exception)
				{
					continue;
				}
				break;
			}
			formFamily3DView.Close();
			return Autodesk.Revit.UI.Result.Succeeded;
		}
	}
}
